<script lang="ts" setup>
import { ref, h, reactive, onMounted,onBeforeMount } from "vue";
import { ReVxeGrid } from "@/components/ReVxeTable";
import { VxeGridPropTypes, VxeUI } from "vxe-table";
import { VxeFormProps, VxeButton } from "vxe-pc-ui";
import { listTaxSourcesRole } from "@/api/workers/workers";
import type { UploadProps } from "element-plus";
import { upload } from "@/utils/uploadCos";
import { Plus } from "@element-plus/icons-vue";
import refundDetail from './components/refundDetail.vue'
import { ElMessage } from "element-plus";
import {
  refundList,
  refundAudit,
  refundOrderState,
  listMerchantName
} from "@/api/capital/capital";
const reVxeGridRef = ref();
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
let taxSourcesId = Number(sessionStorage.getItem("taxSourcesId"))
onBeforeMount(() => {
  if (!Number.isNaN(Number(route.query?.state))) { 
    formOptions.data.state = Number(route.query?.state);
  }
})
onMounted(() => {
  gettaxlist(); //税源地
  getstate();//类型
});
const taxList = ref([]);
const gettaxlist = () => {
  listTaxSourcesRole({ taxSourcesState: 1 }).then((res: any) => {
    taxList.value = res?.data?.rows;
  });
};
// 状态
const stateOptions = ref<any[]>();
const getstate = ()=>{
  refundOrderState().then(res => {
    stateOptions.value = res.data;
  })
}
// 类型
const typeOptions = ref<any[]>([{
  label: '后台申请',
  value: 1
},{
  label: '商户申请',
  value: 2
}])
const columns: VxeGridPropTypes.Columns<any> = [
  // { type: "checkbox", title: "", width: 60, align: "center" },
  {
    title: "退款单号",
    field: "refundNumber",
    align: "center",
    minWidth: 100
  },{
    title: "退款商户",
    field: "merchantsInfoIdDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "税源地",
    field: "taxSourcesIdDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "通道名称",
    field: "bankName",
    align: "center",
    minWidth: 100
  },
  {
    title: "退款户名",
    field: "merchantsName",
    align: "center",
    minWidth: 100
  },
  {
    title: "退款户号",
    field: "merchantsAccount",
    align: "center",
    minWidth: 100
  },
  {
    title: "金额",
    field: "refundAmount",
    align: "center",
    minWidth: 100
  },
  {
    title: "类型",
    field: "refundOrderTypeDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "状态",
    field: "stateDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "理由",
    field: "remark",
    align: "center",
    minWidth: 100
  },
  {
    title: "创建时间",
    field: "createTime",
    align: "center",
    minWidth: 100
  },
  {
    title: "系统流水号",
    field: "flowNumber",
    align: "center",
    minWidth: 100
  },
  {
    title: "创建人",
    field: "createUserIdDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "操作",
    field: "operate",
    align: "center",
    fixed: `right`,
    minWidth: 250,
    slots: {
      default: ({ row }) => {
        let list = [
            h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "查看",
              onClick() {
                 refundDetailRef.value.showAddModal(row.id);
              }
            }),
            h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "审核通过",
              async onClick() {
                const type = await VxeUI.modal.confirm("请确认是否审核通过？");
                if (type == "confirm") {
                  chnagestate(row.id, 4);
                }
              }
            }),
            h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "审核驳回",
              onClick() {
                remark.value = "";
                dialogTableVisible.value = true;
                dialogId.value = row.id;
              }
            }),
            h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "确认退款",
              onClick() {
                remark.value = "";
                dialogTableVisible.value = true;
                dialogId.value = row.id;
              }
            })
          ]
        if(row.state == 1){
          return [list[0],list[1],list[2]]
        }else if(row.state == 2){
          return [list[0],list[1],list[3]]
        }else{
          return [list[0]]
        }
      }
    }
  }
];

const dialogTableVisible = ref<boolean>(false);
const dialogId = ref<number | string>();
const remark = ref<number | string>();
const chnagestate = (id: number | string, type: number) => {
  refundAudit({
    id: id,
    state: type,
    remark: remark.value,
    refundVoucher: form.refundVoucher
  }).then(res => {
    ElMessage.success("操作成功!");
    handleSearch();
  });
};
// 关闭驳回弹窗
const toclose = () => {
  dialogTableVisible.value = false;
  dialogId.value = "";
  remark.value = "";
};
const tosub = () => {
  chnagestate(dialogId.value, 3);
  toclose();
};
// 查看详情

const refundDetailRef = ref();

// 筛选相关
const formRef = ref();
interface FormDataVO {
  refundNumber: number | string; // 退款单号
  merchantsName: string; //服务商name
  merchantsTitle: string; //服务商name
  merchantsInfoId: number | string; //服务商
  merchantsAccount: number | string; //账户户号
  taxSourcesId: number | string; //税源地
  state: number | string; // 状态
  createTimeStart: number | string; //开始日期
  createTimeEnd: number | string; //结束日期
  timeRang: string[]; //日期数组
  refundOrderType: string | number;
}
const formOptions = reactive<VxeFormProps<FormDataVO>>({
  data: {
    refundNumber: "",
    merchantsName: "",
    merchantsTitle: '',
    merchantsInfoId: "",
    merchantsAccount: "",
    taxSourcesId: taxSourcesId,
    // bankName: "",
    state: "",
    createTimeStart: "",
    createTimeEnd: "",
    timeRang: [],
    refundOrderType: ''
  },
  items: [
    {
      field: "refundNumber",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "refundNumber" }
    },
    {
      field: "merchantsName",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "merchantsName" }
    },
    {
      field: "merchantsAccount",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "merchantsAccount" }
    },
    {
      field: "merchantsTitle",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "merchantsTitle" }
    },
    {
      field: "refundOrderType",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "refundOrderType" }
    },
    {
      field: "state",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "state" }
    },
    {
      field: "timeRang",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "timeRang" }
    },
    { align: "left", span: 4, slots: { default: "active" } }
  ]
});

// 服务商搜索
const fetchSuggestions = (queryString: any, cb: (params: any) => void) => {
  let subdata = <
    {
      merchantsName: string;
    }
  >{
    merchantsName: queryString
  };
  listMerchantName(subdata).then(result => {
    cb(result?.data?.rows);
  });
};
const autoselect = (res: any) => {
  console.log(res);
  formOptions.data.merchantsInfoId = res.id;
  formOptions.data.taxSourcesId = "";
  gettaxlist();
};
// 重置内容
const handleInitialFormParams = () => {
  formOptions.data = <FormDataVO>{
    refundNumber: "",
    merchantsName: "",
    merchantsInfoId: "",
    merchantsAccount: "",
    taxSourcesId: "",
    bankAccountType: "",
    state: "",
    createTimeStart: "",
    createTimeEnd: "",
    timeRang: []
  };
};
const handleSearch = () => {
  if (formOptions.data?.timeRang?.length) {
    formOptions.data.createTimeStart = formOptions.data.timeRang[0];
    formOptions.data.createTimeEnd = formOptions.data.timeRang[1];
  } else {
    formOptions.data.createTimeStart = "";
    formOptions.data.createTimeEnd = "";
  }
  reVxeGridRef.value.loadData();
};
const handleReset = async () => {
  await handleInitialFormParams();
  reVxeGridRef.value.loadData("reset");
};

const createModalRef = ref();
const handleAdd = () => {
  createModalRef.value.showAddModal();
};
const handleEdit = (record: Recordable) => {
  createModalRef.value.showEditModal(record);
};

const handleDelete = async (record: Recordable) => {
  const type = await VxeUI.modal.confirm("您确定要删除吗？");
  if (type == "confirm") {
    // deleteData(record.id).then(() => {
    //   handleSearch();
    // });
  }
};

const handleView = (record: Recordable) => {
  createModalRef.value.showViewModal(record);
};
const functions: Record<string, string> = {
  add: "platform.client.index.add",
  edit: "platform.client.index.edit",
  view: "platform.client.index.view",
  delete: "platform.client.index.delete"
};


// 审核通过
const form = reactive<any>({
  refundVoucher: ''
})
const rules = reactive<FormRules<RuleForm>>({
  refundVoucher: [{ required: true, message: "请上传退款凭证", trigger: "blur" }]
});
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  console.log(imageUrl.value);
};
const toupload = (params: any) => {
  upload(params.file, res => {
    console.log(res);
    form.refundVoucher = `https://${res}`
  });
};

const tosubtwo = () => {
  chnagestate(dialogId.value, 5);
  toclose();
};
</script>
<template>
  <div>
    <el-card :shadow="`never`">
      <vxe-form ref="formRef" v-bind="formOptions">
        <template #refundNumber="{ data }">
          <el-input
            clearable
            placeholder="请输入退款单号"
            v-model="data.refundNumber"
          ></el-input>
        </template>
        <template #merchantsName="{ data }">
          <el-input
            clearable
            placeholder="请输入退款户名"
            v-model="data.merchantsName"
          ></el-input>
        </template>
        <template #merchantsAccount="{ data }">
          <el-input
            clearable
            placeholder="请输入退款户号"
            v-model="data.merchantsAccount"
          ></el-input>
        </template>

        <template #merchantsTitle="{ data }">
          <el-autocomplete
            clearable
            v-model="data.merchantsTitle"
            :fetch-suggestions="fetchSuggestions"
            placeholder="请选择退款商户"
            value-key="merchantsName"
            @select="autoselect"
          >
          </el-autocomplete>
        </template>
        <!-- <template #taxSourcesId="{ data }">
          <el-select
            clearable
            placeholder="请选择签约税源地"
            v-model="data.taxSourcesId"
          >
            <el-option
              v-for="(item, index) in taxList"
              :key="index"
              :label="item.taxSourcesName"
              :value="item.taxSourcesId"
            ></el-option>
          </el-select>
        </template> -->
        <!-- <template #bankName="{ data }">
          <el-select
            clearable
            placeholder="请选择通道"
            v-model="data.bankName"
          >
            <el-option
              v-for="(item, index) in bankOptions"
              :key="index"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </template> -->
        <template #refundOrderType="{ data }">
          <el-select clearable placeholder="请选择类型" v-model="data.refundOrderType">
            <el-option
              v-for="(item, index) in typeOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <template #state="{ data }">
          <el-select clearable placeholder="请选择状态" v-model="data.state">
            <el-option
              v-for="(item, index) in stateOptions"
              :key="index"
              :label="item.desc"
              :value="item.code"
            ></el-option>
          </el-select>
        </template>
        <template #timeRang="{ data }">
          <el-date-picker
            clearable
            style="width: 100%"
            v-model="data.timeRang"
            type="daterange"
            range-separator="-"
            value-format="YYYY-MM-DD"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </template>
        <template #active>
          <el-button @click="handleSearch" native-type="submit" type="primary"
            >搜索</el-button
          >
          <el-button @click="handleReset" native-type="reset">重置</el-button>          
        </template>
      </vxe-form>
    </el-card>
    <el-card :shadow="`never`" class="table-card">
      <ReVxeGrid
        ref="reVxeGridRef"
        :request="refundList"
        :functions="functions"
        :searchParams="formOptions.data"
        :columns="columns"
        :action="false"
        @handleAdd="handleAdd"
        @handleView="handleView"
        @handleDelete="handleDelete"
      />
    </el-card>

    <!-- 审核驳回 -->
    <el-dialog v-model="dialogTableVisible" title="审核驳回" width="800">
      <div>
        <el-input
          type="textarea"
          v-model="remark"
          placeholder="请输入驳回原因"
        ></el-input>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="toclose">取消</el-button>
          <el-button type="primary" @click="tosub"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 确认退款 -->
    <el-dialog v-model="dialogTableVisible" title="审核驳回" width="800">
      <div>
        <el-form :model="form" :rules="rules" label-width="250px">
          <el-form-item label="退款凭证" prop="refundVoucher">
             <el-upload
                class="avatar-uploader"
                action="#"
                method="get"
                accept=".png,.jpg,.jpeg"
                :limit="1"
                :with-credentials="true"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :http-request="toupload"
              >
                <!--  
                -->
                <img v-if="form.refundVoucher" :src="form.refundVoucher" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                <template #tip>
                  <div class="el-upload__tip">
                    支持上传扩展名: png/jpg/jpeg 的文件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
        </el-form>
        <div>确认后将扣除商户余额</div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button @click="toclose">取消</el-button> -->
          <el-button type="primary" @click="tosubtwo"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看详情 -->
    <refundDetail ref="refundDetailRef" @reload="handleSearch" />
  </div>
</template>
<style>
.form_header {
  font-size: 15px;
  color: #6379bb;
  border-bottom: 1px solid #ddd;
  padding-bottom: 5px;
}
.left-title {
  font-weight: 700;
  font-family: 微软雅黑;
  font-size: 14px;
  width: 85px;
  text-align: right;
}
.right-text {
  font-size: 14px;
}



.avatar-uploader .el-upload {
  border: 1px dashed #eee;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #eee;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 138px;
  height: 138px;
  text-align: center;
}
.avatar {
  width: 138px;
  height: 138px;
}
.e_footer {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  background: #fff;
}
</style>
